﻿using System;
using System.Net;
using System.Windows.Navigation;
using INdTFramework.Extensions;
using INdTFramework.Http.OAuth;
using INdTFramework.Model;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace INdTFramework.Controls
{
    public partial class FacebookButtonView : PhoneApplicationPage
    {
        private const string SuccessLoginPath = "/connect/login_success.html";

        private FacebookAuth fbc;
        public FacebookData FacebookUserData { get; set; }
        public String Url { get; set; }
        public String RedirectURI { get; set; }

        public FacebookButtonView()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            string appId;
            string secret;
            string scope;
            string destination;
            string clearcookies;

            NavigationContext.QueryString.TryGetValue("appid", out appId);
            NavigationContext.QueryString.TryGetValue("secret", out secret);
            NavigationContext.QueryString.TryGetValue("scope", out scope);
            NavigationContext.QueryString.TryGetValue("destination", out destination);
            NavigationContext.QueryString.TryGetValue("clearcookies", out clearcookies);

            if (clearcookies == "True")
                WebView.ClearCookiesAsync();

            RedirectURI = destination;

            fbc = new FacebookAuth(appId, secret, scope);
            WebView.Source = new Uri(fbc.GetLoginUrl(), UriKind.RelativeOrAbsolute);
        }

        private void WebView_Navigated(object sender, NavigationEventArgs e)
        {
            if (WebView.Source.LocalPath == SuccessLoginPath)
            {

                String code = e.Uri.GetParamenter("code");
                WebClient webClient = new WebClient();

                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ProcessTokenResponse);
                webClient.DownloadStringAsync(new Uri(fbc.GetAccessTokenRequestUrl(code)));
            }
        }

        protected void ProcessTokenResponse(object sender, DownloadStringCompletedEventArgs e)
        {
            fbc.AccessToken = e.Result.GetParamenter("access_token");

            WebClient webClient = new WebClient();

            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ProcessUserIdResponse);
            webClient.DownloadStringAsync(new Uri(fbc.GetIdUser(fbc.AccessToken)));
        }

        protected void ProcessUserIdResponse(object sender, DownloadStringCompletedEventArgs e)
        {
            FacebookUserData = JsonConvert.DeserializeObject<FacebookData>(e.Result);
            RedirectURI += "?id={0}&name={1}&picture={2}";
            RedirectURI = String.Format(RedirectURI, FacebookUserData.Id,
                FacebookUserData.Name, FacebookUserData.Picture.data.url);

            NavigationService.Navigate(new Uri(RedirectURI, UriKind.Relative));
        }
    }
}